<template>
  <view class="container screen-width">
    <view class="content-info">
      <view class="title">商业计划书服务介绍</view>
    </view>
    <van-uploader class="btn-box flex flex-center" accept="file" :maxCount="1" :before-read="beforeRead">
      <view class="btn">检测商业计划书</view>
    </van-uploader>
    <view class="tips">支持ppt、pptx、pdf格式文件检测，推荐pdf</view>
    <!-- <web-view src="../../../hybrid/html/file.html"></web-view> -->
    <!-- <progress id="progressBar" value="0" max="100" style="width: 300px;"></progress>
    <span id="percentage"></span><span id="time"></span> -->
    <!-- <view class="progress">
        <view class="progress-bar progress-bar-striped"
           :style="{ width: files[0].uploadPercentage+'%' }"></view>
      </view> -->
    <view class="file-text">文件上传进度</view>
    <van-progress :percentage="files.uploadPercentage" stroke-width="5" />
    <van-popup v-model="showFile">
      <van-circle layer-color="#ebedf0" v-model="currentRate" :rate="rate" :speed="10" text="分析中" />
    </van-popup>
  </view>
</template>

<script>
  import { uploadFile } from '@/util/uploadBusiness.js'
  import { isWeixin, wxShareConfig } from "@/util/wx.js";
  export default {
    data() {
      return {
        ifOnShow: false,
        files: {
          uploadPercentage: 0
        },
        showFile: false,
        currentRate: 0,
        rate: 0,
        rateArr: []
      }
    },
    onLoad() {
      var arr  = new Array(10).fill(0)
      for(var i=0;i<100;i++){
          var num = parseInt(Math.random()*10)
          arr[num] ++
      }
      this.rateArr = arr
      
      // arr.map(item=>{
      //   this.rate = this.currentRate + item
      // })
    },
    onShow() {
      let token = this.$getToken()
      if (!token) {
        uni.showModal({
          title: '提示',
          content: '您还没有登录，请登录后操作！',
          cancelText: '取消', // 取消按钮的文字
          confirmText: '去登录', // 确认按钮文字
          confirmColor: '#1678ff',
          success: res => {
            if (res.confirm) {
              uni.setStorageSync('pageUrl', window.location.href)
              uni.navigateTo({
                url: '/pages/login/index',
              })
            } else {
              uni.switchTab({
                url: `/pages/index/index`,
              })
            }
          },
        })
      } 
      if (isWeixin()) {
        this.initShareConfig();
      }
    },
    onHide() {
      this.files.uploadPercentage = 0
    },
    methods: {
      beforeRead(file) {
        if (file.size > 10 * 1024 * 1024) {
          uni.showToast({
            title: "文件大小不能超过10M",
            duration: 2000,
            icon: "none"
          });
          return
        }
        
        var fileObj = this.files
        let formData = new FormData()
        // console.log('----------222222', res, file.name)
        formData.append('file', file, file.name)
        let params = formData.get('file')
        // console.log('-----------------', params)

        // http://192.168.2.131:7002
        // https://bootapi.51bmj.cn
        var url = 'https://bootapi.51bmj.cn/bmj-api/api/cms/businessPlanEvaluation/evaluationBusinessPlan';
        var xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        xhr.onload = function () {         
          // 请求完成
          var data = JSON.parse(xhr.responseText);
          if (this.status === 200) {                
            if (data.success == true) {
              this.showFile = true
              for(var i=0;i<this.rateArr.length;i++){
                this.rate = this.rate + arr[i]
              }
              if(this.rate == 100) {
                this.showFile = false
                //  uni.hideLoading()
                uni.navigateTo({
                  url: `/pages/business/detail/Index?id=${data.result}`,
                })
              }
              // setTimeout(()=>{
                // uni.hideLoading()
                // uni.navigateTo({
                //   url: `/pages/business/detail/Index?id=${data.result}`,
                // })
                // this.files.uploadPercentage = 0
              // },5000)
            } else {
              uni.showToast({
                title: data.message,
                icon: "none"
              });
              this.files.uploadPercentage = 0
              uni.hideLoading();
            }
          } else {
            uni.showToast({
              title: '上传失败，请重试',
              icon: "none"
            });
          }
        };
        var formdata = new FormData();
        formdata.append('file', params);
        xhr.setRequestHeader('X-Access-Token', uni.getStorageSync("Mtoken"));

        xhr.upload.addEventListener('progress', function (e) {
          // console.log(fileObj)
          fileObj.uploadPercentage = Math.round((e.loaded * 100) / e.total); 
                  
          // console.log(fileObj.uploadPercentage)
        }, false);
        this.files.uploadPercentage = fileObj.uploadPercentage
        xhr.send(formdata);
        
      },

      uploadFile(files) {
        var p = new Promise(function (resolve, reject) {
          var url = 'https://bootapi.51bmj.cn/bmj-api/api/cms/businessPlanEvaluation/evaluationBusinessPlan';
          var xhr = new XMLHttpRequest();
          xhr.open('POST', url, true);
          xhr.onload = function () {
            // 请求完成
            var data = JSON.parse(xhr.responseText);
            if (this.status === 200) {       
              if (data.success == true) {
                resolve(data);
              } else {
                resolve(data);
              }
            } else {
              resolve('上传失败');
            }
          };
          var formdata = new FormData();
          formdata.append('file', files);
          xhr.setRequestHeader('X-Access-Token', Authorization);

          xhr.upload.addEventListener('progress', function (e) {
            fileObj.uploadPercentage = Math.round((e.loaded * 100) / e.total); 
          }, false);
          this.files.uploadPercentage = fileObj.uploadPercentage
          
          xhr.send(formdata);
        });
        return p;
      },
      // 传入blob路径，.then()获取blob文件
      httpRequest(src) {
        return new Promise((resolve, reject) => {
          let xhr = new XMLHttpRequest()
          xhr.open('GET', src, true)
          xhr.responseType = 'blob'
          xhr.onload = function (e) {
            if (this.status == 200) {
              let myBlob = this.response
              let files = new window.File([myBlob], myBlob.type, { type: myBlob.type })
              resolve(files)
            } else {
              reject(false)
            }
          }
          xhr.send()
        })
      },
      initShareConfig() {
        let _this = this;
        let windowurl = window.location.href.split("#")[0];
        uni.request({
          url: "https://oldm.51bmj.cn/WeiXin/GetClientSign", //仅为示例，并非真实接口地址。
          data: {
            rawUrl: windowurl
          },
          dataType: "json",
          header: {
            "X-Requested-With": "XMLHttpRequest"
          },
          method: "GET",
          success: res => {
            if (res.statusCode == 200) {
              let { data } = res;
              let shareInfo = {
                title: "商业计划书测评",
                desc: "快速精准测评商业计划书，助力企业获得更好的融资",
                link: window.location.href
              };
              // console.log(99999999, data, shareInfo);
              wxShareConfig(this.$wx, data, shareInfo);
            }
          }
        });
      }
    },
  }
</script>

<style lang="less" scoped>
  /deep/ .u-upload__wrap {
    justify-content: center;
  }
  /deep/.van-popup{
    padding: 40rpx;
  }
  .container {
    padding: 30rpx;
    box-sizing: border-box;
    .file-upload{
      font-size: 26rpx;
      background: #1678ff;
      color: #ffffff;
      width: 300rpx;
      text-align: center;
      height: 50rpx;
      line-height: 50rpx;
      border-radius: 20rpx;
      margin: 30rpx auto 0 auto;
      cursor: pointer;

    }
    .content-info {
      padding-bottom: 50rpx;
      .title {
        font-size: 34rpx;
        font-weight: bold;
        text-align: center;
        height: 60rpx;
        line-height: 60rpx;
      }
    }
    .btn-box {
      width: 100%;
      .btn {
        font-size: 26rpx;
        background: #1678ff;
        color: #ffffff;
        width: 300rpx;
        text-align: center;
        height: 50rpx;
        line-height: 50rpx;
        border-radius: 20rpx;
      }
    }
    .tips {
      margin-top: 20rpx;
      font-size: 24rpx;
      color: #bbbbbb;
      width: 100%;
      text-align: center;
      margin-bottom: 40rpx;
    }
    .file-text{
      margin-top: 20rpx;
      font-size: 24rpx;
      color: #333333;
      width: 100%;
      margin-bottom: 20rpx;
    }
  }
</style>
